clear
insheet using "$sourcedatadir/wtid/view_election.csv"
append  using "$gendatadir/view_election_pres.dta"

// Drop European Parliament elections
drop if election_type == "ep"

gen edate = date(election_date, "YMD")
format edate %td

// Calculate Gallagher disproportionality index
gen seat_share = seats / seats_total
gen gallerror = ((seat_share - (vote_share/100))^2)/(vote_share/100)
sort election_id
by election_id: egen galldisp = total(gallerror)
replace galldisp = galldisp * 100

// Calculate the Effective Number of Parties
gen sq_seat_share = (seat_share)^2
by election_id: egen effnumparties = total(sq_seat_share)
replace effnumparties = 1/effnumparties

sort country_name_short edate
by country_name_short edate: drop if _n > 1

keep country_name_short country_name country_id election_id edate galldisp effnumparties

// Lag the two variables of interest by one election period so that they correspond
// to up-to-election incumbency situation, not post-election situation.
by country_name_short: gen electioncount = _n
encode country_name_short, gen(ccode)
tsset ccode electioncount
gen gdl1 = l.galldisp
summ gdl1 
replace galldisp = gdl1 
drop gdl1 
gen enpl1 = l.effnumparties  
replace effnumparties = enpl1 
drop enpl1

drop ccode electioncount

save "$gendatadir/party_system_features.dta", replace
